package com.xjoyt.pay.abstracts;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.xjoyt.pay.dto.PageParam;

@Transactional(readOnly = false, rollbackFor = Throwable.class)
public abstract class AbstractService {

	protected static final Logger logger = LoggerFactory.getLogger(AbstractService.class);

	protected Pageable getPageable(PageParam<?> param) {
		if (StringUtils.isBlank(param.sort)) {
			return new PageRequest(param.page - 1, param.rows);
		}
		Sort pageSort = new Sort(StringUtils.isBlank(param.order) || "DESC".equals(param.order.toUpperCase())
				? Direction.DESC : Direction.ASC, param.sort);
		Pageable pageable = new PageRequest(param.page - 1, param.rows, pageSort);
		return pageable;
	}

	// protected Pageable getFirstPageable() {
	// Pageable pageable = new PageRequest(0, 1);
	// return pageable;
	// }

	protected String toJson(Object obj) {
		if (obj == null) {
			return null;
		}
		Gson gson = new Gson();
		String json = gson.toJson(obj);
		return json;
	}
	
	@SuppressWarnings("unchecked")
	protected <T> T getObject(Class<T> cls, Map<String, Object> args) {
		String key = cls.getSimpleName();
		if (!args.containsKey(key)) {
			return null;
		}
		Object value = args.get(key);
		return (T) value;
	}
	
	protected <T> void putObject(Object obj, Map<String, Object> args) {
		if (obj == null) {
			return;
		}
		Class<?> cls = obj.getClass();
		String key = cls.getSimpleName();
		if (args.containsKey(key)) {
			args.remove(key);
		}

		args.put(key, obj);
	}
}
